﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace RockBus.ServiceBus
{
    /// <summary>
    ///
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class RockBusMessageAttribute : Attribute
    {
        /// <summary>
        /// The Topic of the message body. Can/will be used to evaluate against Topic Filters.
        /// </summary>
        public string DefaultTopic { get; set; }

        /// <summary>
        /// The SOAP action of the message body. Used to uniquely identify the message type.
        ///  Specify if compatibility with an existing WCF service is required.
        ///  If not specified, the Type.Name will be used.
        /// </summary>
        public string Action { get; set; }

        public bool IsResponse { get; set; }

        private Type _appliedToType;

        public Type AppliedToType { get { return _appliedToType; } }

        public static IEnumerable<RockBusMessageAttribute> ScanAssemblies(IEnumerable<Assembly> assemblies)
        {
            foreach (Assembly ass in assemblies)
            {
                foreach (Type type in ass.GetTypes())
                {
                    RockBusMessageAttribute rbma = ScanType(type);
                    if (null != rbma)
                    {
                        yield return rbma;
                    }
                }
            }
        }

        public static RockBusMessageAttribute ScanType(Type type)
        {
            object[] attrs = type.GetCustomAttributes(typeof(RockBusMessageAttribute), true);
            if ((null == attrs) || (attrs.Length != 1))
            {
                return null;
            }

            RockBusMessageAttribute rbma = attrs[0] as RockBusMessageAttribute;
            if (string.IsNullOrEmpty(rbma.Action))
            {
                rbma.Action = type.FullName;
            }
            rbma._appliedToType = type;
            return rbma;
        }
    }
}